<?php
/**
 * Created by PhpStorm.
 * User: LYQ
 * Date: 2020/4/1
 * Time: 15:08
 */

namespace app\api\model;
use think\db;
use app\api\model\RedisManagerModel;

class RedisModel
{
    public $redis_db_no = "db01";//默认使用 db01

    /**
     * 删除redis的key
     * @param type $key
     * @return boolean
     */
    public static function redisDelKey($key)
    {
        RedisManagerModel::getInstance()->del($key);
        return true;
    }

    /*
     * 读 redis，将数据以json的格式存入
     * @param $key
     * @param null $value
     * @return mixed|null
     */
    public static function get_from_redis($key, $value = null)
    {
        if (!is_null($value)) {
            RedisManagerModel::getInstance()->set($key, json_encode($value, true));
        }
        $result = RedisManagerModel::getInstance()->get($key);
        return $result ? json_decode($result, true) : null;
    }

    /*
     * 读redis，将数据 以 list 数据格式存入
     * @param $key
     * @param $start 起始值
     * @param $length 长度
     * @param null $value
     * @return
     */
    public static function get_list_from_redis($key, $start = 0, $length = 0, $value = null)
    {
        if (!is_null($value)) {
            // list 数据类型，当有新的数据应该将旧数据清除
            RedisManagerModel::getInstance()->delete($key);
            foreach ($value as $item) {
                RedisManagerModel::getInstance()->lPush($key, json_encode($item, true));
            }
        }
        if ($length === 0) {
            $length = RedisManagerModel::getInstance()->lLen($key);
        }

        $lst = RedisManagerModel::getInstance()->lGetRange($key, $start, $length);
        if ($lst) {
            $result = array();
            foreach ($lst as $item) {
                array_push($result, json_decode($item, true));
            }
            return $result;
        }
        return null;
    }
    /*
     * 将数据 以 set 数据格式存入
     * @param $key
     * @param $start 起始值
     * @param $length 长度
     * @param null $value
     * @return
     */
    public static function set_from_redis($key, $value)
    {
        return phpinfo();
//        return RedisManagerModel::getInstance()->sadd($key,$value);
    }
}